package com.guli.gulimall.authserver.controller;

import com.alibaba.fastjson.TypeReference;
import com.guli.common.constant.AuthServerConstant;
import com.guli.common.exception.BizCodeEnum;
import com.guli.common.utils.R;
import com.guli.gulimall.authserver.feign.MemberFeignService;
import com.guli.gulimall.authserver.feign.ThirdPartFeignService;
import com.guli.gulimall.authserver.vo.UserLoginVo;
import com.guli.gulimall.authserver.vo.UserRegistVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.validation.Valid;
import javax.validation.constraints.NotEmpty;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Controller
public class LoginController {
    
    @Autowired
    ThirdPartFeignService thirdPartFeignService;

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    MemberFeignService memberFeignService;

    /**
     * 发送一个请求直接跳转到一个页面
     * SpringMvc viewcontroller,将请求和页面映射过来
     *
     * 实现 WebMvcConfigurer
     * 重写 addViewControllers()
     *
     * @return
     */

//    @GetMapping(value = {"/","/login.html"})
//    public String loginPage(){
//
//        return "login";
//    }
//
//    @GetMapping("/reg.html")
//    public String regPage(){
//
//        return "reg";
//    }

    @GetMapping("/sms/sendCode")
    @ResponseBody
    public R sendCode(@RequestParam("phone") String phone){
        //1.接口防刷
        String redisCode = redisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + phone);
        if(!StringUtils.isEmpty(redisCode)){
            Long time = Long.parseLong(redisCode.split("_")[1]);
            if(System.currentTimeMillis() - time < 60000){
                //60s内不能再存
                return R.error(BizCodeEnum.SMS_CODE_EXCEPTION.getCode(),BizCodeEnum.SMS_CODE_EXCEPTION.getMsg());
            }
        }
        //2.验证码的字词校验 redis,key=phone,value=code ; sms:code13585891802 -> 12211
        String code = UUID.randomUUID().toString().substring(0, 5);
        String subString = code + "_" + System.currentTimeMillis();
        //验证码15分钟有效，防止一个phone再60s内重复发送验证码
        redisTemplate.opsForValue().set(AuthServerConstant.SMS_CODE_CACHE_PREFIX + phone,subString,15, TimeUnit.MINUTES);
        thirdPartFeignService.sendCode(phone,code);
        return R.ok();
    }

    /**
     * 用户注册
     * todo 重定向携带数据，利用session原理，将数据存放在session中。只要跳到下一个页面，取出这个数据以后，session里面的数据就会删掉。
     * todo 分布式session问题
     * RedirectAttributes redirectAttributes： 模拟重定向携带数据
     *
     * @param userRegistVo
     * @param result
     * @param model
     * @param redirectAttributes
     * @return
     */
    @PostMapping("/regist")
    public String regist(@Valid UserRegistVo userRegistVo, BindingResult result, Model model, RedirectAttributes redirectAttributes){
        if(result.hasErrors()){
            /**
             * map(fieldError -> {
             *                 String field = fieldError.getField();
             *                 String defaultMessage = fieldError.getDefaultMessage();
             *                 errors.put(field,defaultMessage);
             *             })
             */
            Map<String, String> errors = result.getFieldErrors().stream().collect(Collectors.toMap(FieldError::getField,FieldError::getDefaultMessage));
//            model.addAttribute("errors",errors);
            redirectAttributes.addFlashAttribute("errors",errors);//addFlashAttribute 只用一次
            //报错：Request method 'POST' not supported 问题原因：用户注册->/regist[post] -> 转发/reg.html (路径映射默认都是get方式访问的。这里是post)
            //校验出错，转发到注册页
//            return "forward:/reg.html";
            //重定向要写完整路径
            return "redirect:http://auth.gulimall.com/reg.html";
        }
        //1.校验验证码
        String code = userRegistVo.getCode();
        String s = redisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + userRegistVo.getPhone());
        if(!StringUtils.isEmpty(s)){
            if(code.equals(s.split("_")[0])){
                //删除验证码
                redisTemplate.delete(AuthServerConstant.SMS_CODE_CACHE_PREFIX + userRegistVo.getPhone());
                //验证通过，真正注册，调用远程服务
                R r = memberFeignService.regist(userRegistVo);
                if(r.getCode()==0){
                    //成功
                    return "redirect:http://auth.gulimall.com/login.html";
                }else{
                    //失败
                    Map<String, String> errors = new HashMap<>();
                    errors.put("msg",r.getData("msg",new TypeReference<String>(){}));
                    redirectAttributes.addFlashAttribute("errors",errors);
                    return "redirect:http://auth.gulimall.com/reg.html";
                }
            }else{
                //验证码错误
                Map<String, String> errors = new HashMap<>();
                errors.put("code","验证码错误");
                redirectAttributes.addFlashAttribute("errors",errors);
                return "redirect:http://auth.gulimall.com/reg.html";
            }
        }else{
            //验证码空了
            Map<String, String> errors = new HashMap<>();
            errors.put("code","验证码过期");
            redirectAttributes.addFlashAttribute("errors",errors);
            return "redirect:http://auth.gulimall.com/reg.html";
        }
    }


    @PostMapping("/login")
    public String login(UserLoginVo userLoginVo,RedirectAttributes redirectAttributes){
        //远程登录
        R r = memberFeignService.login(userLoginVo);
        if(r.getCode()==0){
            //登录成功
            return "redirect:http://gulimall.com";
        }else{
            //登录失败
            Map<String, String> errors = new HashMap<>();
            errors.put("msg",r.getData("msg",new TypeReference<String>(){}));
            redirectAttributes.addFlashAttribute("errors",errors);
            return "redirect:http://auth.gulimall.com/login.html";
        }
    }



}
